var appPath = getAppPath();	

$(function(){
	// 主的分类(检索用)
	$("#queryTmplType").combobox({
		url:appPath+'/itbStats/getTypeForCombo.action?topIds=1,2,4,6,7,8,1010,1011,1020,1030&blkFlg=1',
		valueField:'type_id',//默认为不选选了后将参数传给type_id
		textField:'type_name',
		onSelect:function(selRecd){
			$("#queryTmplType2").combobox("clear");
			$("#queryTmplType3").combobox("clear");
			$("#queryTmplType2").combobox("loadData",{});
			$("#queryTmplType3").combobox("loadData",{});	
			// 中间分类
			var parentId=selRecd.type_id;
			if(Number(parentId)>0){
				$("#queryTmplType2").combobox({
					url:appPath+'/itbStats/getTypeForCombo.action?parent='+parentId+'&blkFlg=1',
					valueField:'type_id',
					textField:'type_name',
					onSelect:function(selRecd2){
						$("#queryTmplType3").combobox("clear");
						$("#queryTmplType3").combobox("loadData",{});
						
						// 小分类
						var parentId2=selRecd2.type_id;
						if(Number(parentId2)>0){
							$("#queryTmplType3").combobox({
								url:appPath+'/itbStats/getTypeForCombo.action?parent='+parentId2+'&blkFlg=1',
								valueField:'type_id',
								textField:'type_name',
								onSelect:function(selRecd3){
									// TODO
								}
							});
						}
					}
				});
			}
		}
	});

	// 用户id 查看用户作品
	$("#queryUserId").combobox({
		url:appPath+'/itbCoupon/getOrgUserForCombo.action?blkFlg=1&orgId=1',
		valueField:'id',
		textField:'name',
		onSelect:function(selRecdU){
			// TODO
		}
	});
	
	// 主的分类(设置用)
	$("#batchType").combobox({
		url:appPath+'/yjxStats/getTypeForCombo.action?topIds=1,2,4,6,7,8,1010,1011,1020,1030&blkFlg=1',
		valueField:'type_id',
		textField:'type_name',
		onSelect:function(selRecd){
			$("#batchType2").combobox("clear");
			$("#batchType3").combobox("clear");
			$("#batchType2").combobox("loadData",{});
			$("#batchType3").combobox("loadData",{});	
			// 中间分类
			var parentId=selRecd.type_id;
			if(Number(parentId)>0){
				$("#batchType2").combobox({
					url:appPath+'/yjxStats/getTypeForCombo.action?parent='+parentId,
					valueField:'type_id',
					textField:'type_name',
					onSelect:function(selRecd2){
						$("#batchType3").combobox("clear");
						$("#batchType3").combobox("loadData",{});
						
						// 小分类
						var parentId2=selRecd2.type_id;
						if(Number(parentId2)>0){
							$("#batchType3").combobox({
								url:appPath+'/yjxStats/getTypeForCombo.action?parent='+parentId2,
								valueField:'type_id',
								textField:'type_name',
								onSelect:function(selRecd3){
									// TODO
								}
							});
						}
					}
				});
			}
		}
	});
	// 检索日期范围
	$("#queryDateStart").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	$("#queryDateEnd").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	$('#playUserVideoDlg').window({
		onBeforeClose:function(){ 
			document.getElementById('userVideoInfo').pause();
		}
	});
	
	initJspGrid();
});
function dtFmt(dt){
	var y = dt.getFullYear();
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);//格式化mm-dd
}
function dtParser(s){
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        return new Date(y,m-1,d);
    } else {
        return new Date();
    }
}

// 样版列表初始化
function initJspGrid(){
	$('#tmplGrid').datagrid({
	    url:appPath + "/yjxStats/getMapInfoList.action",
	    height:'full',
	    remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
			//微缩图
		    {field:'thumb',title:'缩略图',width:90,align:'center',sortable:false,
	        	formatter:function(thumb, rowData, rowIndex){
	        		var retUrl = '';
					if (thumb) {
						retUrl = '<a href="' + thumb + '" target="_blank">'
							+ '<div style="display:table;text-align:center;height:110px;width:100%">'
							+ '<span style="display:table-cell;vertical-align:middle">'
							+ '<img src="' +thumb+'?x-oss-process=image/resize,m_lfit,h_120,w_100'
							+ '" style="display:inline;max-height:100px;max-width:100px"></span></div></a>';
					}
					return retUrl;
	        	}
		    },
	        {field:'uni_item_id',title:'统一ID',width:40,align:'center',sortable:false},
	        {field:'design_id',title:'模版ID',width:40,align:'center',sortable:false},
	        {field:'relAplyCnt',title:'<font color="#DC143C">应用数[实]</font>',width:60,align:'center',sortable:true,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<a href="javasript:void(0)" style="color:#DC143C;" onclick="showApply('+rowData.design_id+','+rowData.top_type+')">查看</br><font face="verdana">'+Number(value||'0')+'</font></a>';
	        	}
	        },
	        {field:'applyCnt',title:'<span style="color:blue;font-size:1px;">应用数[显]</span>',width:65,align:'center',sortable:true,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<a href="javascript:void(0)" onclick="editApplyCnt('+rowData.stats_id+','+rowData.applyCnt+')"><font face="verdana">'+Number(value||'0')+'</font></a>';
	        	}
	        },
	        {field:'coll_num',title:'<font color="green" face="verdana">收藏数</font>',width:55,align:'center',sortable:true,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<font face="verdana" color="green">'+Number(value||'0')+'</font>';
	        	}
	        },
	        {field:'orderCnt',title:'<font color="red">下单数</font>',width:60,align:'center',sortable:true,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<font face="verdana" color="red">'+Number(value||'0')+'</font>';
	        	}
	        },
	        {field:'buyCnt',title:'<font color="green">买单数</font>',width:60,align:'center',sortable:true,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<font face="verdana" color="green">'+Number(value||'0')+'</font>';
	        	}
	        },
		    {field:'top_type',title:'主分类',width:50,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return clkType(value);
		    	  }
		      },
			{field:'editType',title:'子分类',width:60,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
					  return rowData.type_name || '<span style="color:red">未分类</span>';
				  }
			},
		    {field:'design_name',title:'设计模版名称',width:110,align:'left',sortable:false},
		    {field:'user_id',title:'设计师',width:60,align:'left',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if (value){
		    			return '<font color="blue;">ID:'+value+'<br>'+rowData.nickname+'</font>';
		    		}
		    		return '<font color="red">设计师被删</font>';
		    	}
		    },
		    {field:'size_id',title:'尺寸(W*H)',width:60,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return '('+(rowData.width||'N/A')+')<br>*<br>('+(rowData.height||'N/A')+')';
		    	  }
		    },			        
		    {field:'create_time',title:'创建时间',width:55,align:'center',sortable:false},			        
		    {field:'update_time',title:'更新时间',width:55,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar: [
          {
			text:'刷新APP端模版应用次数',
			iconCls:'icon-reload',
			handler:function(){
				showRefreshDlg();
			}
		  },
		  '-',
		  {
		    text:'批量设置应用次数',
		    iconCls:'icon-reload',
		    handler:function(){
		    	showBatchDlg();
		    }
		  }
        ]
	});
}

function clkType(value){
	 var tn = '未知';
	  switch(Number(value||'0')){
	  	case 1: tn='单页';break;
	  	case 2: tn='多页';break;
	  	case 3: tn='PPT';break;
	  	case 4: tn='印品';break;
	  	case 6: tn='社交媒体';break;
	  	case 7: tn='电商';break;
	  	case 8: tn='微商';break;
	  	case 1010: tn='LOGO商品';break;
	  	case 1011: tn='营销商品';break;
	  	case 1020: tn='视频';break;
	  	case 1030 : tn ='视频背景';break;
	  }
	  return tn;
}

// 展示单个模板  用户的作品列表
function showApply(designId,topType){
	$("#udocForm").form('clear');
	$("#uDocTable").show();
	$("#designId").html(designId);
	var tn = clkType(topType);
	$("#topType").html(tn);
	// 买单状态 
	$("#payState").combobox({
		data : [{"id":0,"name":"不限"},{"id":1,"name":"已买单"}],
		valueField : 'id',
		textField : 'name',
		onLoadSuccess:function(rel){
			$("#payState").combobox('select',0);
		}
	});
	
	// 用户属性
	$("#testFlg").combobox({
		data : [{"id":'',"name":"[全部]"},{"id":0,"name":"真实用户"},{"id":1,"name":"测试用户"}],
		valueField : 'id',
		textField : 'name',
		onLoadSuccess:function(rel){
			$(this).combobox('select','');
		}
	});
	
	$("#uDocDlg").window({
		title :'单个模板下的用户作品',
		iconCls :'icon-blank',
		modal :true,
		shadow :true,
		collapsible :false,
		minimizable :false,
		maximizable :false
	});
	$('#uDocDlg').window('move',{top:20,left:20});
	$('#uDocDlg').window('open');
	
	initUserDoc(designId,topType);
}

function initUserDoc(designId,topType){
	$('#uDocGrid').datagrid({
	    url:appPath + "/yjxStats/pageGetUserDocInfo.action?disId="+designId+"&topType="+topType,
	    height:'full',
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam3(),
	    singleSelect:true,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    columns:[[
			{field : 'thumbs',title : '缩略图',width : 30,align : 'center',sortable : false,
				formatter : function(value, rowData, rowIndex) {
					var retUrl = '';
					if (value){
						var video = rowData.video;
						if (video === undefined ){
							var st = rowData.uni_doc_id +","+rowData.user_id;
	        				 var en = encrypt(st);
	        				 var url = getYjxHomeServer()+"/yjx/v1_0_0/outside/share?v="+en;
							retUrl = '<a href="'+url+'" target="_blank">'
							+ '<div style="display:table;text-align:center;height:90px;width:100%;">'
							+ '<span align="center" style="display:table-cell;vertical-align:middle">'
							+ '<img src="'+value+'?x-oss-process=image/resize,m_fixed,h_120,w_100'
							+ '" style="display:inline;max-height:90px;max-width:70px;"/></span></div></a>';
						} else {
							var thumb = JSON.parse(value);
							if (thumb == null || thumb.length<=0) {
								thumb = 'http://itbour-user.oss-cn-hangzhou.aliyuncs.com/image/U2/2017/11/06/191334526_2eKu1A5k5LmGoc4fezKI.jpg';
							}
							retUrl = '<a href="javascript:void(0)" onclick="playUserDocVideo(\''+thumb+'\',\''+video+'\')">'
							+ '<div style="display:table;text-align:center;height:70px;width:100%;">'
							+ '<span align="center" style="display:table-cell;vertical-align:middle">'
							+ '<img src="'+thumb+'?x-oss-process=image/resize,m_fixed,h_60,w_100'
							+ '" style="display:inline;max-height:70px;max-width:70px;"/></span></div></a>';
						}
					}
					return retUrl;
				}
			},
			{field:'doc_id',title:'作品ID',width:20,align:'center',sortable:false},
	        {field:'doc_name',title:'文档名称',width:50,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(value){
  	        			return '<span style="color:	#555555;">'+value+'</span>';
  	        		}
	        		return '<span style="color:#B0B0B0;">暂无</span>';
	        	}
		    },
		    {field :'user_id',title :'用户ID', width:25, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		var ret = '';
		    		if (rowData.test_flg == 1){
		    			ret = '<font color="red">Test</font>';
		    		}
		    		if(value){
		    			return '<font style="color:#555555;">'+value+'</font><br/>'+ret;
		    		}
		    	}
		    },
		    {field :'nickname',title :'用户昵称', width:45, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if(value){
		    			return '<span style="color:#436EEE;">'+value+'</span>';
		    		}
		    		return '<span style="color:#9C9C9C;">暂无</span>';
		    	}
		    },
		    {field :'mobile',title :'手机号', width:30, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		return value || '<span style="color:#9C9C9C">暂未填写</span>';
		    	}
		    },
		    {field :'state',title :'买单状态', width:30, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if (value){
		    			return '<span style="color:red;">已买单</span>';
		    		}
		    		return '未买单';
		    	}
		    },
		    {field:'eidtDoc',title:'编辑',width:30,align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		return '<a href="javascript:void(0)" onclick="eiditDocInfo('+rowData.uni_doc_id+','+rowData.user_id+')">修改</a>';
		    	}
		    },
	        {field:'create_time',title:'创建时间',width:50,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:50,align:'center',sortable:false}
	    ]],
	    pagination:true,
		rownumbers:true,
		toolbar:[]
	});
}

function eiditDocInfo(unDocId,userId){
	$.messager.confirm('确认','<font color="red">修改用户作品信息,将无法还原到最初的作品样式,是否确认继续修改用户作品?</font>',function(r){
		if (r){
			window.open(getYjxWebServer()+'/backChangeUserPro?userId='+userId+'&id='+unDocId+'');
		}
	});
}

//播放视频资源
function playUserDocVideo(thumb,videoUrl){
	$('#playUserVideoDlg').window({
		title:'视频播放',
		iconCls:'icon-tip',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	if (!videoUrl){
		return $.messager.alert('警告','该视频资源暂无..','warning');
	}
	
	$('#playUserVideoDlg').window('move',{top:20,left:200});
	$('#playUserVideoDlg').window('open');
	var retUrl = '<a href="'+thumb+'" target ="_blank" '
	+ '<div style="display:table;text-align:center;height:150px;width:100%;">'
	+ '<span style="display:table-cell;vertical-align:middle">'
	+ '<img src="' +thumb+'?x-oss-process=image/resize,m_lfit,h_146,w_250'
	+ '" style="display:inline;max-height:150px;max-width:400px"></span></div></a>';
	
	$("#userVideoThumb").html(retUrl);
	
	var htm = '<video style="margin-left:20px;height:270px;" id="userVideoInfo" controls="controls" preload="auto" poster="'+thumb+'" src="'+videoUrl+'"></video>';
	$("#userViderUrl").html(htm);
}

//一键秀  接口加密
function encrypt(strIn){
	var strOut = '';
    if(strIn && strIn.length>0) {
        var arr = strIn.split(',');
        if(arr && arr.length<=5) {
            var arrSEP = [
                {R:26,S:'v'},
                {R:27,S:'w'},
                {R:28,S:'x'},
                {R:29,S:'y'},
                {R:30,S:'z'}
            ];
            for(var i=0; i<arr.length; i++) {
                var SEP = arrSEP[i];

                if(arr[i] && arr[i].length>0) {
                    var num = Number(arr[i]);
                    strOut += num.toString(SEP.R);
                }
                strOut += SEP.S;
            }
        }
    }
    return strOut;
}

//	视频用户文档
function doQuery3(){
	$("#uDocGrid").datagrid('unselectAll');
	$("#uDocGrid").datagrid('load', getQueryParam3());
}

function getQueryParam3(){
	var obj = {};
	var docId = $("#queryDocId").val();
	var userId = $("#queryDocUserId").val();
	var mobile = $("#queryMobile").val();
	
	var findState = $("#payState").combobox('getValue');
	var findTestFlg = $("#testFlg").combobox('getValue');
	
	if (Number(findState)>0) obj.findState = findState;
	if (Number(findTestFlg)>=0) obj.findTestFlg = findTestFlg;
	if(Number(docId)>0) obj.findDocId = docId;
	if(Number(userId)>0) obj.findDocUserId = userId;
	if(Number(mobile)>=0){
		obj.findMobile = mobile;
	}else{
		$.messager.alert('提示信息','请输入有效数字!','info');
	} 
	return obj;
}

/*
 * 编辑修改 显示用应用次数
 */
function editApplyCnt(s_id,order){
	$("#viewId").val(s_id);
	$("#viewContent").val(order);
	
	$("#viewBtn").show();
	$('#viewDlg').window({
		title:'编辑[显示用]应用次数',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#viewDlg').window('move',{top:20,left:40});
	$('#viewDlg').window('open',{top:100,left:120});
}

//取消浏览 显示用应用次数
function cancleEditView(){
	$("#viewDlg").window('close');
}

//确定编辑 显示用应用次数
function doEditView(){
	var id=$("#viewId").val();//这条记录的id
	var applyCnt=$("#viewContent").val();//获取输入的浏览次数
	if(!applyCnt || applyCnt.length == 0|| Number(applyCnt)<=0){
		$.messager.alert('提示信息','输入有效数字','warning');
		return;
	}
	var url=appPath+"/yjxStats/editApplyCnt.action?id="+id+"&applyCnt="+applyCnt;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','修改成功！','info',function(){
				doQuery();
				$('#viewDlg').window('close');
			});
		} else {
			$.messager.alert('提示信息','修改失败','warning');
		}
	});
	
}


function showRefreshDlg() {
	$("#refreshBtn").show();
	$('#refreshDlg').window({
		title:'刷新APP端模版［应用次数］显示数据',
		iconCls:'icon-reload',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#refreshDlg').window('move',{top:20,left:20});
	$('#refreshDlg').window('open');
}
function cancelRefresh() {
	$('#refreshDlg').window('close');
}
function doRefresh() {
	var type =$("#refreshType").combobox('getValue');
	$.loading(true);
	var url = getApiServer()+"/callFunc/setYjxTmplApplyCnt?type="+type;
	$.post(url,function(ret){
		$.loading(false);
		if(ret.success){
			$.messager.alert('提示信息','处理模版总数:'+ret.data.GetCnt+
					'<br/>新建:'+ret.data.InsCnt+'  更新:'+ret.data.UpdCnt+
					'<br/>错误:'+ret.data.ErrCnt, 'warning');
		}else {
			$.messager.alert('提示信息','刷新失败！','warning');
		}
	});
}


function showBatchDlg() {
	$("#batchBtn").show();
	$('#batchDlg').window({
		title:'批量设置［应用次数］显示数据',
		iconCls:'icon-reload',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#batchDlg').window('move',{top:20,left:20});
	$('#batchDlg').window('open');
}
function cancelBatchUpd() {
	$('#batchDlg').window('close');
}
function doBatchUpd() {
	var top_type =Number($("#batchType").combobox('getValue')||'0')||0;// 初级分类
	var parent =Number($("#batchType2").combobox('getValue')||'0')||0;// 中间分类
	var type =Number($("#batchType3").combobox('getValue')||'0')||0;// 三级分类
	var base =$("#batchBaseCnt").combobox('getValue');
	var mult=Number($("#batchMult").val()||'0')||0;
	
	if(!mult || mult<=1 || mult>21){
		$.messager.alert('提示信息','请输入有效倍数!</br><span style="color:red">注: 1<倍数<=21(最好不要设置10或20)</span>','warning');
		return;
	}
	
	if(top_type) {
		batchUpdProc();
	} else {
		$.messager.alert('提示信息','必须选一个顶级分类','warning');
		return;
	}
	
	function batchUpdProc() {
		$.loading(true);
		var url = appPath+"/yjxStats/batchSetTmplApplyCnt.action?top_type="+top_type+"&parent="+parent+"&type_id="+type+"&base="+base+"&mult="+mult;
		$.post(url,function(ret){
			$.loading(false);
			if(ret=="ok"){
				$.messager.alert('提示信息','设置成功', 'warning');
				doQuery();
			} else {
				$.messager.alert('提示信息','设置失败！','warning');
			}
		});
	}
}


function getQueryParam(){
	var queryObject = {};
	var findDtS = $("#queryDateStart").datebox('getValue');//获取开始结束日期
	var findDtE = $("#queryDateEnd").datebox('getValue');
	var findPub = $("#queryPublish").combobox('getValue');
	var findTmplType =$("#queryTmplType3").combobox('getValue');
	if(!findTmplType){
		findTmplType =$("#queryTmplType2").combobox('getValue');
	}
	var findTmplTypetop=$("#queryTmplType").combobox('getValue');					
	var findDocName=$("#queryDocName").val().trim();//文档名字	
	if (findTmplType) {
		queryObject.findTmplType = findTmplType;// 类型
	}
	if (findTmplTypetop) {
		queryObject.findTmplTypetop = findTmplTypetop;// 类型
	}
	
	var findUniTmplId = $("#uniTmplId").val();// 获取统一模板ID
	var findUserId = $("#queryUserId").combobox('getValue');
	if (Number(findUniTmplId)>0) queryObject.findUniTmplId = findUniTmplId;
	if (Number(findUserId)>0) queryObject.findUserId = findUserId;
	if(findPub&&findPub.length>0) queryObject.findPubFlg = findPub;// 发布标记
	if(findDocName&&findDocName.length>0) queryObject.findDocName = findDocName;// 样版名称
	if(findDtS && findDtS.length>0) queryObject.findDateStart = findDtS + ' 00:00:00';
	if(findDtE && findDtE.length>0) queryObject.findDateEnd = findDtE+' 23:59:59';
	return queryObject;
}


function doQuery(){
	$("#tmplGrid").datagrid('unselectAll');
	$("#tmplGrid").datagrid('reload',getQueryParam());
	var findDtS = $("#queryDateStart").datebox('getValue');//获取开始结束日期前
	var findDtE = $("#queryDateEnd").datebox('getValue');
	if(findDtS && findDtS.length>0){
		var chkRet = chkInputDate(findDtS);
		$("#queryDateStart").datebox('setValue',chkRet);
	}
	if(findDtE && findDtE.length>0){
		var chkRet = chkInputDate(findDtE);
		$("#queryDateEnd").datebox('setValue',chkRet);
	}
}

//判断日期格式[YYYY-MM-DD]
function chkInputDate(dt){
	 var strDate=dt+'';
    var ss = (strDate.split('-'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        var chkDt = new Date(y,m-1,d);
		if((chkDt.getFullYear()==y) &&((chkDt.getMonth()+1)==m) &&(chkDt.getDate()==d)) {
        	return dtFmt(chkDt);
        }
    }
    return '';
}